package com.sxbbc.api.controller;

import java.util.*;

import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.service.solr.entity.Solrpage;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.FunctionUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.ProductDetailVo;
import com.sxbbc.common.core.dto.jz.ProductVo;
import com.sxbbc.common.core.dto.jz.SearchVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.BusinessScopeEnums;
import com.sxbbc.common.core.enums.ProductTypeEnums;
import com.sxbbc.common.core.enums.SolrSortEnums;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.login.LoginTokenService;
import com.sxbbc.common.core.service.system.solr.SolrproductService;
import com.sxbbc.common.core.service.system.solr.entity.SolrProductDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.common.ProductMapping;
import com.sxbbc.common.core.enums.ClassifyTypeEnums;
import com.sxbbc.common.core.utils.BasePage;

/**
 * 产品/产品有关 控制层
 *
 * @author leehao
 * @date 2019-05-15 16:46
 */
@RestController

public class ProductController {
    @Autowired
    private ProcClassifyMainService classifyMainService;
    @Autowired
    private IProcEvaluateService procEvaluateService;
    @Autowired
    private LoginTokenService loginTokenService;
    @Autowired
    private ICShoppingCartService cShoppingCartService;
    @Autowired
    private IProcMainService procMainService;
    @Autowired
    private IProSkuDetailService proSkuDetailService;
    @Autowired
    private IProcDescribeService procDescribeService;
    @Autowired
    private IProcInterestService procInterestService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private ICCollectProService cCollectProService;
    @Autowired
    private SolrproductService solrProductService;
    @Autowired
    private ActivityService activityService;

    /**
     * 查询所有分类
     *
     * @return 结果集
     * @author leehao
     */
    @Cacheable(value = "bbcCache", key = "'queryClassifyList'")
    @RequestMapping(value = ProductMapping.QUERY_CLASSIFY_LIST)
    public RestResponse queryClassifyList() {
        ProcFirstClassifyMain main = new ProcFirstClassifyMain();
        main.setStatus(StaticUtils.STATUS_YES);
        QueryWrapper<ProcFirstClassifyMain> ew = new QueryWrapper<ProcFirstClassifyMain>(main);
        ew.orderByDesc("sort");
        ew.orderByDesc("sort");
        List<ProcFirstClassifyMain> classifyList = classifyMainService.queryClassifyList(ew);
        return GetRest.getSuccess("success", classifyList);
    }

    /**
     * 根据一级分类查找二级分类
     *
     * @param id    一级分类id
     * @param level 2二级菜单 3三级菜单
     * @return 结果集
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.QUERY_CLASSIFY_BYID)
    public RestResponse queryClassifyByFirstId(Integer id, Integer level) {
        List<?> secondList = classifyMainService.queryClassifyListAjax(id, ClassifyTypeEnums.PLAT_FORM.getId(), null, level);
        return GetRest.getSuccess("success", secondList);
    }

    /**
     * 搜索产品 solr搜索
     *
     * @param productVo 商品vo对象
     * @param search    搜索vo对象
     *                  sortType 排序类型
     *                  sortDesc 升序asc 降序desc
     * @param cpage     页码 默认1
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.QUERY_PRODUCT_LIST)
    public RestResponse queryProductList(ProductVo productVo,
                                         SearchVo search,
                                         @RequestParam(defaultValue = "1") Integer cpage) {
        //只对价格设置升序降序
        if (!CalcuUtils.getInstance().isEquals(search.getSortType(), SolrSortEnums.PRICE.getId())) {
            search.setSortDesc("asc");
        }
        Solrpage<SolrProductDto> page = procMainService.queryProductListBySolr(productVo, cpage, search);
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("product", page);
        return GetRest.getSuccess("success", map);
    }

    /**
     * 查询商品评论数量(全部和有图)
     *
     * @param proCode 产品编号
     * @return Map total 全部评论数   hasPhoto  有图评论数
     */
    @RequestMapping(value = ProductMapping.GET_PRO_EVALUATE_NUM)
    public RestResponse getProEvaluateNum(String proCode) {
        Map<String, Object> map = procEvaluateService.getProEvaluateNum(proCode);
        return GetRest.getSuccess("", map);
    }

    /**
     * 查询商品评论集合
     *
     * @param page     分页
     * @param proCode  商品编号
     * @param hasPhoto 是否有图查询
     * @return 分页数据
     */
    @RequestMapping(value = ProductMapping.QUERY_PRO_EVALUATE_LIST)
    public RestResponse queryProEvaluateList(BasePage<ProcEvaluate> page, String proCode, Integer hasPhoto) {
        IPage<ProcEvaluate> pageInfo = procEvaluateService.queryProEvaluateList(page, proCode, hasPhoto);
        return GetRest.getSuccess("", pageInfo);
    }

    /* 购物车部分 */

    /**
     * 我的购物车列表
     *
     * @param token 获取cid
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.QUERY_SHOPPING_LIST)
    public RestResponse queryMyShoppingCart(String token, Integer type,Integer bid) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        List<CShoppingCart> list = null;
        if (CalcuUtils.getInstance().isEquals(type, BusinessScopeEnums.ONLINE.getId())) {
            list = cShoppingCartService.queryMyShoppingCart(cid);
        } else if (CalcuUtils.getInstance().isEquals(type, BusinessScopeEnums.OFFLINE.getId())) {
            list = cShoppingCartService.queryMyShoppingCartByNearBussiness(cid,bid);
        }
        list.forEach(x -> x.setCid(null));
        return GetRest.getSuccess("success", list);
    }

    /**
     * 删除购物车商品
     *
     * @param token 获取cid
     * @param ids   要删除的记录id
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.DELETE_SHOPPING_CART)
    public RestResponse deleteMyShoppingCart(String token, Integer[] ids) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        if (ids == null || ids.length <= 0) {
            return GetRest.getFail("您还没有选择商品哦");
        }
        List<Integer> idList = FunctionUtils.getList(ids);
        boolean delete = cShoppingCartService.removeByIds(idList);
        if (!delete) {
            throw new ThrowJsonException("删除购物车商品失败");
        }
        return GetRest.getSuccess("删除成功");
    }

    /**
     * 加入购物车
     *
     * @param token 获取cid
     * @param cart  购物车对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.ADD_SHOPPING_CART)
    public RestResponse addShoppingCart(String token, CShoppingCart cart) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("请先登录哦～");
        }
        if (StringUtils.isBlank(cart.getProCode())) {
            return GetRest.getFail("请选择商品");
        }
        if (StringUtils.isBlank(cart.getSku()) && cart.getSkuId() == null) {
            return GetRest.getFail("请选择商品规格");
        }
        ProcMain procMain = procMainService.selectOneByProCode(cart.getProCode());
        if (!CalcuUtils.getInstance().isEquals(procMain.getProType(), ProductTypeEnums.NORMAL.getId())) {
            return GetRest.getFail("只有普通商品可以加入购物车哦～");
        }
        cart.setCid(cid);
        cart.setType(cart.getType());
        boolean add = cShoppingCartService.addShoppingCart(cart);
        if (!add) {
            throw new ThrowJsonException("商品加入购物车失败");
        }
        return GetRest.getSuccess("加入成功");
    }

    /**
     * 编辑购物车数量
     *
     * @param token 获取cid
     * @param id    记录id
     * @param qty   数量
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.EDIT_SHOPPING_CART_QTY)
    public RestResponse editShoppingQty(String token, Integer id, Integer qty) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        if (id == null) {
            return GetRest.getFail("被选中的商品异常");
        }
        if (qty == null || qty < 1) {
            return GetRest.getFail("商品数量太少了哦");
        }
        CShoppingCart cart = new CShoppingCart();
        cart.setId(id);
        cart.setCid(cid);
        cart.setQty(qty);
        boolean update = cShoppingCartService.updateById(cart);
        if (!update) {
            throw new ThrowJsonException("处理失败");
        }
        return GetRest.getSuccess("成功");
    }

    /* ------- 商品详情部分 ------- */

    /**
     * 商品详情
     * 商品基本信息
     *
     * @param token     获取cid
     * @param productVo vo对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    /*  @AccessLimit(seconds = 30, maxCount=30)*/
    @RequestMapping(value = ProductMapping.SHOW_PRODUCT_DETAIL)
    public RestResponse showProductDetail(String token, ProductVo productVo) {
        if (StringUtils.isNotBlank(token)) {
            Integer cid = loginTokenService.validLoginCid(token);
            if (cid != null) {
                productVo.setCid(cid);
            }
        }
        System.out.println("商品详情访问token" + token);
        //商品信息
        ProductDetailVo productDetailVo = procMainService.selectProductDetail(productVo);
        return GetRest.getSuccess("", productDetailVo);
    }

    /**
     * 获取商品库存和价格
     *
     * @param productVo proCode 商品编码
     *                  sku 选中的规格
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.SELECT_PRODUCT_PRICE_AND_STOCK)
    public RestResponse selectPriceAndStock(ProductVo productVo) {
        if (StringUtils.isBlank(productVo.getProCode())) {
            return GetRest.getFail("获取商品信息失败");
        }
        if (StringUtils.isBlank(productVo.getSku())) {
            return GetRest.getFail("请选择至少一项规格");
        }
        ProductDetailVo productDetailVo = proSkuDetailService.selectPriceAndStock(productVo);
        return GetRest.getSuccess("success", productDetailVo);
    }

    /**
     * 商品图文详情页
     *
     * @param proCode 商品编码
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @GetMapping(value = ProductMapping.SHOW_PRODUCT_DESCRIBE)
    public RestResponse showProductDescribe(String proCode) {
        ProcDescribe procDescribe = procDescribeService.selectByProCode(proCode);
        return GetRest.getSuccess("", procDescribe.getPcDetails());
    }

    /**
     * 商品权益
     *
     * @param proCode 商品编码
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = ProductMapping.GET_PRODUCT_INTEREST)
    public RestResponse getProductInterest(String proCode) {
        if (StringUtils.isBlank(proCode)) {
            return GetRest.getFail("获取商品编码失败");
        }
        ProcMain procMain = procMainService.selectOneByProCode(proCode);
        if (procMain == null) {
            return GetRest.getFail("该商品不存在");
        }
        QueryWrapper<ProcInterest> wrapper = new QueryWrapper<ProcInterest>();
        List<ProcInterest> interestList = new ArrayList<>();
        if (StringUtils.isNotBlank(procMain.getInterest())) {
            wrapper.eq("status", StaticUtils.STATUS_YES).
                    in("id", Arrays.asList(procMain.getInterest().split(",")));
            interestList = procInterestService.list(wrapper);
        }
        return GetRest.getSuccess("", interestList);
    }

    /**
     * 处理商品收藏与取消
     *
     * @param token       获取cid
     * @param proCode     商品编号
     * @param collectFlag 收藏标记 1收藏 0取消
     * @return 结果
     * @author xiaoky
     */
    @RequestMapping(value = ProductMapping.HANDLE_PRO_COLLECT)
    public RestResponse handleProCollect(String token, String proCode, Integer collectFlag) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        if (StringUtils.isBlank(proCode)) {
            return GetRest.getFail("获取商品信息失败");
        }
        return cCollectProService.handleProCollect(cid, proCode, collectFlag);
    }

}
